#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
# @Time    : 2021/8/7 15:45
# @Author  : YHSimon
import os

fileName = 'student.txt'


def main():
    while True:
        menu()
        choice = int(input('请选择:'))
        if choice in [0, 1, 2, 3, 4, 5, 6, 7]:
            if choice == 0:
                answer = input('您确定要退出系统吗？y/n\n')
                if answer == 'y' or answer == 'Y':
                    print('感谢您的使用！！！')
                    break
                else:
                    continue
            elif choice == 1:
                insert()
            elif choice == 2:
                search()
            elif choice == 3:
                delete()
            elif choice == 4:
                update()
            elif choice == 5:
                sort()
            elif choice == 6:
                count()
            else:
                show()


def menu():
    print('=====================学生信息管理系统====================')
    print('------------------------功能菜单-----------------------')
    print('\t\t\t\t1.录入学生信息')
    print('\t\t\t\t2.查找学生信息')
    print('\t\t\t\t3.删除学生信息')
    print('\t\t\t\t4.修改学生信息')
    print('\t\t\t\t5.排序')
    print('\t\t\t\t6.统计学生总人数')
    print('\t\t\t\t7.显示所有学生信息')
    print('\t\t\t\t0.退出系统')
    print('------------------------------------------------------')


def insert():
    stu_list = []
    while True:
        sid = input('请输入学生ID(如1001):')
        if not sid:
            break
        name = input('请输入姓名:')
        if not name:
            break
        try:
            english = int(input('请输入英语成绩:'))
            python = int(input('请输入Python成绩:'))
            java = int(input('请输入Java成绩:'))
        except:
            print('输入无效，非整型，请重新输入！！！')
            continue
        student = {'id': sid, 'name': name, 'English': english, 'Python': python, 'Java': java}
        stu_list.append(student)
        answer = input('是否继续添加?y/n\n')
        if answer == 'y' or answer == 'Y':
            continue
        else:
            break
    # 调用save()函数
    save(stu_list)
    print('学生信息录入完毕！！！')


def save(lst):
    try:
        stu_txt = open(fileName, 'a', encoding='UTF-8')
    except:
        stu_txt = open(fileName, 'w', encoding='URF-8')
    for item in lst:
        stu_txt.write(str(item) + '\n')
    stu_txt.close()


def search():
    stu_query = []
    while True:
        sid = ''
        name = ''
        if os.path.exists(fileName):
            mode = input('按ID查询请按1，按姓名查询请按2:')
            if mode == '1':
                sid = input('请输入学生id:')
            elif mode == '2':
                name = input('请输入学生姓名:')
            else:
                print('您的输入有误！请重新输入！！！')
                search()
            with open(fileName, 'r', encoding='utf-8') as rFile:
                student = rFile.readlines()
                for item in student:
                    d = dict(eval(item))
                    if sid != '':
                        if d['id'] == sid:
                            stu_query.append(d)
                    elif name != '':
                        if d['name'] == name:
                            stu_query.append(d)
            # 显示查询结果
            show_stu(stu_query)
            # 清空列表
            stu_query.clear()
            answer = input('是否继续查询?y/n\t')
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break
        else:
            print('暂未保存学生信息')
            return


def show_stu(lst):
    if len(lst) == 0:
        print('没有查询到学生信息，无数据显示！！！')
        return
    else:
        # 定义标题的显示格式
        format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
        print(format_title.format('ID', '姓名', '英语成绩', 'Python成绩', 'Java成绩', '总成绩'))
        # 定义内容的显示格式
        format_data = '{:^6}\t{:^14}\t{:^10}\t{:^10}\t{:^10}\t{:^10}'
        for item in lst:
            print(format_data.format(item.get('id'),
                                     item.get('name'),
                                     item.get('English'),
                                     item.get('Python'),
                                     item.get('Java'),
                                     int(item.get('English')) + int(item.get('Python')) + int(item.get('Java'))
                                     ))


def delete():
    while True:
        sid = input('请输入要删除要删除学生信息的id：')
        if sid != '':
            if os.path.exists(fileName):
                with open(fileName, 'r', encoding='UTF-8') as file:
                    stu_old = file.readlines()
            else:
                stu_old = []
            flag = False  # 标记是否删除
            if stu_old:
                with open(fileName, 'w', encoding='UTF-8') as wFile:
                    d = {}
                    for item in stu_old:
                        d = dict(eval(item))  # 将字符串转成字典
                        if d['id'] != sid:
                            wFile.write(str(d) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f'id为{sid}的学生信息已被删除')
                    else:
                        print(f'没有找到id为{sid}的学生信息')
            else:
                print('无学生信息')
                break
            show()
            answer = input('是否继续删除学生信息吗?y/n\n')
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break


def update():
    show()
    if os.path.exists(fileName):
        with open(fileName, 'r', encoding='UTF-8') as rFile:
            student_old = rFile.readlines()
    else:
        return
    sid = input('请输入要修改的学生id：')
    with open(fileName, 'w', encoding='UTF-8') as wFile:
        for item in student_old:
            d = dict(eval(item))
            if d['id'] == sid:
                print('找到学生信息，可以修改他/她的相关信息！')
                while True:
                    try:
                        d['name'] = input('请输入姓名:')
                        d['English'] = input('请输入英文成绩:')
                        d['Python'] = input('请输入英文成绩:')
                        d['Java'] = input('请输入英文成绩:')
                    except:
                        print('您的输入有误，请重新输入！！！')
                    else:
                        break
                wFile.write(str(d) + '\n')
                print('修改成功！！！')
            else:
                wFile.write(str(d) + '\n')
        answer = input('是否修改其他学生的信息?y/n\n')
        if answer == 'y' or answer == 'Y':
            update()


def sort():
    show()
    if os.path.exists(fileName):
        with open(fileName, 'r', encoding='utf-8') as rFile:
            stu_list = rFile.readlines()
        stu_new = []
        # 将字符串类型转成字典类型
        for item in stu_list:
            d = dict(eval(item))
            stu_new.append(d)
    else:
        return
    asc_or_desc = input('请选择( 0.升序  1.降序 )')
    if asc_or_desc == '0':
        asc_or_desc_bool = False  # 升序
    elif asc_or_desc == '1':
        asc_or_desc_bool = True  # 降序
    else:
        print('您的输入有误,请重新输入!!!')
        sort()
    mode = input('请选择排序方式:(1.按英语成绩排序 2.按Python成绩排序 3.按Java成绩排序 0.按总成绩排序)')
    if mode == '1':
        # x是参数 且为字典 并把结果赋值给key
        stu_new.sort(key=lambda x: int(x['English']), reverse=asc_or_desc_bool)
    elif mode == '2':
        stu_new.sort(key=lambda x: int(x['Python']), reverse=asc_or_desc_bool)
    elif mode == '3':
        stu_new.sort(key=lambda x: int(x['Java']), reverse=asc_or_desc_bool)
    elif mode == '0':
        stu_new.sort(key=lambda x: int(x['English']) + int(x['Python']) + int(x['Java']), reverse=asc_or_desc_bool)
    else:
        print('您的输入有误,请重新输入!!!')
        sort()
    show_stu(stu_new)


def count():
    if os.path.exists(fileName):
        with open(fileName, 'r', encoding='UTF-8') as rFile:
            stu_list = rFile.readlines()
            if stu_list:
                print(f'一共有{len(stu_list)}名学生')
            else:
                print('还未录入学生信息!!!')
    else:
        print('暂未保存数据信息....')


def show():
    if os.path.exists(fileName):
        stu_list = []
        with open(fileName, 'r', encoding='utf-8') as rFile:
            students = rFile.readlines()
        for item in students:
            stu_list.append(eval(item))
        if stu_list:
            show_stu(stu_list)
        else:
            print('还未录入学生信息!!!')
    else:
        print('暂未保存数据信息....')


if __name__ == '__main__':
    main()
